﻿using soma.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace soma.Models
{
    public class TagsSplitter
    {
        public static List<Tag> SplitAndDistributeTags(string tags, int results)
        {
            string[] tagArray = TagsSplitter.SplitTags(tags);

            int noResultsPerTag = results / tagArray.Count();
            int moduloResultsTag = results % tagArray.Count();

            List<Tag> tagList = new List<Tag>();
            foreach (string tagName in tagArray)
            {
                if (moduloResultsTag > 0)
                {
                    moduloResultsTag--;
                    tagList.Add(new Tag(tagName.Trim(), noResultsPerTag + 1));
                }
                else
                {
                    tagList.Add(new Tag(tagName.Trim(), noResultsPerTag));
                }
            }

            return tagList;
        }

        public static void DivideResultBetweenTagAndSynonyms(Tag tag)
        {
            // The tag will get half of the search, and the synonyms will get the rest devided equally
            // If there are synonyms with 0 result left, we eliminate them
            if (tag.Synonyms.Count != 0)
            {
                int totalResults = tag.NumberResults;
                tag.NumberResults = totalResults / 2 + totalResults % 2;
                totalResults -= tag.NumberResults;

                int equalSynonyms = totalResults / tag.Synonyms.Count;
                int modulo = totalResults % tag.Synonyms.Count;

                foreach (Tag synonym in tag.Synonyms)
                {
                    synonym.NumberResults = equalSynonyms;
                    if (modulo != 0)
                    {
                        synonym.NumberResults++;
                        modulo--;
                    }
                }

                for (int i = 0; i < tag.Synonyms.Count; i++)
                {
                    if (tag.Synonyms[i].NumberResults.Equals(0))
                    {
                        tag.Synonyms.RemoveAt(i);
                    }
                }
            }
        }

        public static string[] SplitTags(string tags)
        {
            // The keywords are separated by , and ;. The space will be considered part of an expression
            return tags.Split(Constants.TAGS_SEPARATORS);
        }
    }
}